package com.yk.i_wms.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yk.i_wms.common.model.Result;
import com.yk.i_wms.dto.SmsReturnDocDTO;
import com.yk.i_wms.mapper.SmsReturnDocMapper;
import com.yk.i_wms.model.*;
import com.yk.i_wms.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 退料入库单
 *
 * @author hbq
 * @date 2021-04-14 13:37:08
 */
@Slf4j
@Service
public class SmsReturnDocServiceImpl extends ServiceImpl<SmsReturnDocMapper, SmsReturnDoc> implements ISmsReturnDocService {
    @Resource
    private SmsReturnDocMapper smsReturnDocMapper;
    @Autowired
    private ISmsReturnDocDetailService smsReturnDocDetailService;
    @Autowired
    private ISmsReturnDocRecordService smsReturnDocRecordService;
    @Autowired
    private ISmsOutStockDocRecordService smsOutStockDocRecordService;
    @Autowired
    private ISmsStockInfoService smsStockInfoService;
    @Autowired
    private ISmsBarcodeService smsBarcodeService;

    /**
     * 列表
     * @param params
     * @return
     */
    public Page<Map> findList(Map<String, Object> params){
        Integer pageNum = MapUtils.getInteger(params, "pageNum");
        Integer pageSize = MapUtils.getInteger(params, "pageSize");
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = -1;
        }
        Page<Map> pages = new Page<>(pageNum, pageSize);
        return smsReturnDocMapper.findList(pages, params);
    }
    @Override
    public Result saveAll(SmsReturnDocDTO smsReturnDocDTO) {
        SmsReturnDoc smsReturnDoc=smsReturnDocDTO;
        if (smsReturnDoc.getDocState()!=1){
            return Result.failed("非新建状态不允许修改");
        }
        log.info("新建或更新退料入库单：{}",smsReturnDocDTO);
        String docNo =StrUtil.isBlank(smsReturnDocDTO.getDocNo())?getNewNo():smsReturnDocDTO.getDocNo();
        smsReturnDoc.setDocNo(docNo);
        //删除原有docNo的详情
        smsReturnDocDetailService.remove(new LambdaQueryWrapper<SmsReturnDocDetail>().eq(SmsReturnDocDetail::getDocNo,docNo));
        smsReturnDocRecordService.remove(new LambdaQueryWrapper<SmsReturnDocRecord>().eq(SmsReturnDocRecord::getDocNo,docNo));
        List<SmsReturnDocDetail> smsReturnDocDetails = smsReturnDocDTO.getSmsReturnDocDetails();
        List<SmsReturnDocRecord> smsReturnDocRecords = smsReturnDocDTO.getSmsReturnDocRecords();
        if (smsReturnDocDetails == null||smsReturnDocDetails.isEmpty()||smsReturnDocRecords == null||smsReturnDocRecords.isEmpty()) {
            return Result.failed(  "详情列表不能为空");
        }
        smsReturnDocDetails.forEach(u->{
            u.setDocNo(docNo);
        });
        saveOrUpdate(smsReturnDoc);
        smsReturnDocDetailService.saveBatch(smsReturnDocDetails);

        for (SmsReturnDocRecord smsReturnDocRecord : smsReturnDocRecords) {
            SmsReturnDocDetail smsReturnDocDetail = smsReturnDocDetailService.getOne(new LambdaQueryWrapper<SmsReturnDocDetail>()
                    .eq(SmsReturnDocDetail::getDocNo, docNo)
                    .eq(SmsReturnDocDetail::getItemCode, smsReturnDocRecord.getItemCode())
            );
            if (smsReturnDocDetail != null) {
                Long id = smsReturnDocDetail.getId();
                smsReturnDocRecord.setDocNo(docNo);
                smsReturnDocRecord.setDdId(id);
            }
            String sn = smsReturnDocRecord.getSn();
            Long qty = smsReturnDocRecord.getQty();
            SmsStockInfo stockInfo = smsStockInfoService.getOne(new LambdaQueryWrapper<SmsStockInfo>()
                    .eq(SmsStockInfo::getSn, sn)
                    .eq(SmsStockInfo::getStockState,2)
            );
            if (stockInfo==null){
                return Result.failed("无此条码信息");
            }
            //修改库存数量
            stockInfo.setQty(qty);
            stockInfo.setStockState(1);
            stockInfo.setIsOpen(1);
            stockInfo.setHasPrint(0);
            smsStockInfoService.updateById(stockInfo);
        }
        smsReturnDocRecordService.saveBatch(smsReturnDocRecords);
        return Result.succeed("保存成功");
    }

    @Override
    public Result close(SmsReturnDoc smsReturnDoc) {
        String docNo = smsReturnDoc.getDocNo();
        SmsReturnDoc returnDoc = getOne(new LambdaQueryWrapper<SmsReturnDoc>().eq(SmsReturnDoc::getDocNo, docNo));
        returnDoc.setDocState(3);
        updateById(returnDoc);
        return Result.succeed("保存成功");
    }

    @Override
    public Result selRecordBySn(Map<String, Object> params) {
        String sn = MapUtil.getStr(params, "sn");
        List<SmsOutStockDocRecord> outStockDocRecords = smsOutStockDocRecordService.list(new LambdaQueryWrapper<SmsOutStockDocRecord>()
                .eq(SmsOutStockDocRecord::getSn, sn)
                .eq(SmsOutStockDocRecord::getState,2)
                .orderByDesc(SmsOutStockDocRecord::getId)
        );
        if (outStockDocRecords.isEmpty()){
            return Result.failed("无此条码信息,或未备料");
        }
        SmsOutStockDocRecord outStockDocRecord = outStockDocRecords.get(0);
        SmsStockInfo stockInfo = smsStockInfoService.getOne(new LambdaQueryWrapper<SmsStockInfo>()
                .eq(SmsStockInfo::getSn, sn)
                .eq(SmsStockInfo::getStockState,2)
        );
        if (outStockDocRecord==null||stockInfo==null){
            return Result.failed("无此条码信息");
        }
        SmsReturnDocRecord smsReturnDocRecord = new SmsReturnDocRecord();
        smsReturnDocRecord.setSn(sn);
        smsReturnDocRecord.setOutDocNo(outStockDocRecord.getDocNo());
        smsReturnDocRecord.setItemCode(stockInfo.getItemCode());
        smsReturnDocRecord.setItemName(stockInfo.getItemName());
        smsReturnDocRecord.setQty(0L);
        smsReturnDocRecord.setPdate(stockInfo.getPdate());
        smsReturnDocRecord.setBatch(stockInfo.getBatch());
        return Result.succeed(smsReturnDocRecord,"查询成功");
    }

    @Override
    public Result updateStock(Map<String, Object> params) {
        String sn = MapUtil.getStr(params, "sn");
        Long qty = MapUtil.getLong(params, "qty");
        SmsStockInfo stockInfo = smsStockInfoService.getOne(new LambdaQueryWrapper<SmsStockInfo>()
                .eq(SmsStockInfo::getSn, sn)
                .eq(SmsStockInfo::getStockState,2)
        );
        if (stockInfo==null){
            return Result.failed("无此条码信息");
        }
        //修改库存数量
        stockInfo.setQty(qty);
        stockInfo.setStockState(1);
        stockInfo.setIsOpen(1);
        stockInfo.setHasPrint(0);
        smsStockInfoService.updateById(stockInfo);
        return Result.succeed("保存成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result delete(Map<String, List<Long>> map) {
        try{
            List<Long> ids = map.get("ids");
            for (Long id : ids) {
                SmsReturnDoc returnDoc = getById(id);
                if (returnDoc.getDocState()!=1){
                    int i=1/0;
                }
                String docNo = returnDoc.getDocNo();
                removeById(id);
                smsReturnDocDetailService.remove(new LambdaQueryWrapper<SmsReturnDocDetail>()
                        .eq(SmsReturnDocDetail::getDocNo,docNo)
                );
            }
            return Result.succeed("删除成功");
        }
        catch (Exception e){
            // 事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.failed( e,"保存失败，单状态非新建");
        }
    }

    /**
     * 获取新的串号
     * @return 当前串号的下一个串号
     */
    private String getNewNo(){
        //生成新的串号
        String prefix="RN" + DateUtil.format(new Date(), "yyyyMMdd");
        String maxNo=prefix+"001";
        SmsReturnDoc one = getOne(new QueryWrapper<SmsReturnDoc>()
                .last("where doc_no like '" + prefix + "%' order by doc_no desc limit 1"));
        if (one != null) {
            Long aLong = Convert.toLong(StrUtil.removePrefix(one.getDocNo(), prefix));
            maxNo=prefix+String.format("%3d",aLong+1).replace(" ","0");
        }
        return maxNo;
    }
}
